package com.dragon.mmochat.service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.dao.DataIntegrityViolationException;

import com.dragon.mmochat.message.Mmochat_16_1C;
import com.dragon.mmochat.model.pkteam.MmochatPkTeam;
import com.dragon.mmochat.model.role.MmochatPlayer;
import com.dragon.mmochat.util.MmochatUtil;
import com.skymobi.handler.SkymobiHandler;
import com.skymobi.message.SkymobiProtocolMessage;
import com.skymobi.service.SkymobiService;

//战队
public class MmochatPkTeamService {
	private static Map<Integer, MmochatPkTeam> pkTeams = new ConcurrentHashMap<Integer, MmochatPkTeam>();

	// 根据ID获取战队
	public static MmochatPkTeam getPkTeamById(int id) {
		MmochatPkTeam pkTeam = pkTeams.get(id);
		if (pkTeam == null) {
			try {
				pkTeam = MmochatDao.getPkTeamById(id);
				pkTeams.put(pkTeam.getId(), pkTeam);
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
		return pkTeam;
	}

	// 创建战队
	@SkymobiService
	public SkymobiProtocolMessage handleC_16_1(SkymobiHandler handler,
			Mmochat_16_1C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}
		synchronized (me) {
			if (me.hasPkTeam()) {
				return MmochatUtil.msgbox(req.getHallState(), "您已经有自己的战队了!");
			}
			String teamName = req.getName();
			if (teamName == null || teamName.length() < 3
					|| teamName.length() > 8) {
				return MmochatUtil.msgbox(req.getHallState(),
						"战队名必需是3到8个字!请重新输入。");
			}
			// 非法字检测
			if (MmochatFilterService.isHasFilterWord(teamName)) {
				return MmochatUtil.msgbox(req.getHallState(),
						"战队名中包含非法字词!请重新输入。");
			}
			// 创建并加入此战队，并将此战队加入到pkTeams中
			try {
				MmochatDao.createPkTeam(me, teamName, pkTeams);
			} catch (DataIntegrityViolationException e) {
				return MmochatUtil.msgbox(req.getHallState(), "该战队名已存在!");
			} catch (Exception e) {
				e.printStackTrace();
				return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
			}
		}
		return MmochatUtil.msgbox(req.getHallState(), "创建成功!请按8键查看战队。");
	}
}
